package coroutines

import kotlinx.coroutines.*


//suspend fun main() = coroutineScope {
//
//    launch {
//        delay(1000)
//        println("Kotlin Coroutines World")
//    }
//
//    println("Hello")
//}


//fun main() = runBlocking {
//    launch {
//        delay(1000)
//        println("World!")
//    }
//    print("Hello ")
//}


//fun main() = runBlocking {
//    launch {
//        doWorld()
//    }
//    print("Hello ")
//}
//
//suspend fun doWorld() {
//    delay(1000)
//    println("World!")
//}


//fun main() = runBlocking {
//    doWorld()
//    println("Done")
//}
//
//suspend fun doWorld() = coroutineScope {
//    launch {
//        delay(2000)
//        println(" World2")
//    }
//
//    launch {
//        delay(1000)
//        print(" World1")
//    }
//
//    print("Hello")
//}


//fun main() = runBlocking {
//
//    launch {
//        println("starting...")
//    }
//
//    val job = launch {
//        delay(1000)
//        println("World!")
//    }
//
//    println("Hello")
//    // job加入 等待job完成再执行下面的步骤
//    job.join()
//    println("Done")
//}


//fun main() = runBlocking {
//
//    repeat(10_000) {
//        launch {
//            delay(5000L)
//            print(".")
//        }
//    }
//
//}


//fun main() = runBlocking {
//    val startTime = System.currentTimeMillis()
//    val job = launch(Dispatchers.Default) {
//        var nextPrintTime = startTime
//        var i = 0
//        while (i < 5) {
//            if (System.currentTimeMillis() >= nextPrintTime) {
//                println("job: I'm sleeping ${i++}...")
//                nextPrintTime += 500
//            }
//        }
//    }
//    delay(1300)
//    println("main: I'm tired of waiting!")
//    job.cancelAndJoin()
//    println("main: Now I can quit.")
//}

//output:
//job: I'm sleeping 0...
//job: I'm sleeping 1...
//job: I'm sleeping 2...
//main: I'm tired of waiting!
//job: I'm sleeping 3...
//job: I'm sleeping 4...
//main: Now I can quit.


fun main() = runBlocking {
    val startTime = System.currentTimeMillis()
    val job = launch(Dispatchers.Default) {
        var nextPrintTime = startTime
        var i = 0
        // TODO 修改了此处
        while (isActive) {
            if (System.currentTimeMillis() >= nextPrintTime) {
                println("job: I'm sleeping ${i++}...")
                nextPrintTime += 500
            }
        }
    }
    delay(1300)
    println("main: I'm tired of waiting!")
    job.cancelAndJoin()
    println("main: Now I can quit.")
}

// output:
//job: I'm sleeping 0...
//job: I'm sleeping 1...
//job: I'm sleeping 2...
//main: I'm tired of waiting!
//main: Now I can quit.